package com.wpf.system.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wpf.system.common.response.ResultUtils;
import com.wpf.system.common.response.ResultVO;
import com.wpf.system.entity.FieldBook;
import com.wpf.system.entity.Orders;
import com.wpf.system.entity.dto.BookRentBuySearchDTO;
import com.wpf.system.entity.dto.FieldBookDTO;
import com.wpf.system.entity.vo.FieldBookVO;
import com.wpf.system.entity.vo.PageVO;
import com.wpf.system.service.BalanceJournalService;
import com.wpf.system.service.FieldBookService;
import com.wpf.system.service.OrdersService;
import com.wpf.system.service.PointJournalService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/fieldBook")
public class FieldBookController {
    @Resource
    private FieldBookService fieldBookService;

    @Resource
    private PointJournalService pointJournalService;

    @Resource
    private OrdersService ordersService;

    @Resource
    BalanceJournalService balanceJournalService;

    @GetMapping("/chart")
    public ResultVO getFieldBookChart(
            @RequestParam(value = "id",required=false) Long id,
            @RequestParam(value = "date",required=false) String date
    ){
        return ResultUtils.success("请求预约图表数据成功",fieldBookService.getFieldBookChart(id,date));
    }

    @GetMapping
    public List<FieldBook> getFieldBook(@RequestParam("fids") String fids, @RequestParam("date") String bookDate){
        return fieldBookService.getFieldBookByDate(Convert.toList(Long.class,fids.split(",")), bookDate);
    }

    @GetMapping("/list")
    public PageVO<FieldBookVO> getAllFieldBook(
            @RequestParam(value = "no",required=false) String no,
            @RequestParam(value = "uid",required=false) Long uid,
            @RequestParam(value = "name",required=false) String name,
            @RequestParam(value = "nid",required=false) String nid,
            @RequestParam(value = "username",required=false) String username,
            @RequestParam(value = "phone",required=false) String phone,
            @RequestParam(value = "startTime",required=false) String startTime,
            @RequestParam(value = "endTime",required=false) String endTime,
            @RequestParam(value = "page",required=false) Integer page,
            @RequestParam(value = "pageSize",required=false) Integer pageSize
    ){
        BookRentBuySearchDTO bookRentBuySearchDTO = new BookRentBuySearchDTO();
        bookRentBuySearchDTO.setNo(no);
        bookRentBuySearchDTO.setUid(uid);
        bookRentBuySearchDTO.setName(name);
        bookRentBuySearchDTO.setNid(nid);
        bookRentBuySearchDTO.setUsername(username);
        bookRentBuySearchDTO.setPhone(phone);
        bookRentBuySearchDTO.setStartTime(startTime);
        bookRentBuySearchDTO.setEndTime(endTime);
        bookRentBuySearchDTO.setPageSize(pageSize);
        //手动分页需要注意分页公式
        if(ObjectUtil.isNotNull(page)&&ObjectUtil.isNotNull(pageSize)){
            bookRentBuySearchDTO.setPage(Math.max((page - 1) * pageSize,0));
        }
        List<FieldBookVO> list = fieldBookService.getAllFieldBook(bookRentBuySearchDTO);
        bookRentBuySearchDTO.setPage(null);
        bookRentBuySearchDTO.setPageSize(null);
        int total = fieldBookService.getAllFieldBook(bookRentBuySearchDTO).size();
        PageVO<FieldBookVO> fieldBookListVO = new PageVO<>();
        fieldBookListVO.setList(list);
        fieldBookListVO.setTotal(total);
        return fieldBookListVO;
    }

    @PostMapping
    public ResultVO addFieldBook(@RequestBody List<FieldBookDTO> fieldBookDTOList){
        List<Long> canBookId = new ArrayList<>();
        for(FieldBookDTO item : fieldBookDTOList){
            if(fieldBookService.checkFieldCanBook(item.getFid(), item.getTid(), Convert.toStr(item.getDate()))){
                FieldBook fieldBook = new FieldBook();
                fieldBook.setUid(item.getUid());
                fieldBook.setFid(item.getFid());
                fieldBook.setTid(item.getTid());
                fieldBook.setBookCost(item.getBookCost());
                fieldBook.setRemark(item.getRemark());
                fieldBook.setBookStartDate(Convert.toDate(item.getBookStartDate()));
                fieldBook.setBookEndDate(Convert.toDate(item.getBookEndDate()));
                if(fieldBookService.save(fieldBook)){ canBookId.add(fieldBook.getId()); }
            }
        }
        if(canBookId.size() == fieldBookDTOList.size() && canBookId.size()>0){
            return ResultUtils.success("已预约以下场次，请在1分钟内确认订单无误",fieldBookService.getFieldBookById(canBookId));
        }else if(canBookId.size() < fieldBookDTOList.size() && canBookId.size()>0){
            return ResultUtils.success("部分预约信息已失效，但仍已预约以下有效场次，请在1分钟内确认继续或取消此次预约",fieldBookService.getFieldBookById(canBookId));
        }else {
            return ResultUtils.error("很抱歉！预约信息失效，请刷新页面再次选择合适的场次");
        }
    }

    @PutMapping
    public ResultVO editFieldBookStatus(@RequestBody FieldBook fieldBook){
        int beforeUpdateStatus = fieldBookService.getById(fieldBook.getId()).getStatus();
        Orders orders = ordersService.getById(fieldBook.getOid());
        boolean flag;
        String msg = null;
        //如果是未支付的订单取消子项，则整个订单取消
        if(orders.getStatus()==0){
            fieldBookService.list(new LambdaQueryWrapper<FieldBook>().eq(FieldBook::getOid,orders.getId())).forEach(item->{
                item.setStatus(fieldBook.getStatus());
                fieldBookService.updateById(item);
            });
            orders.setStatus(2);
            orders.setCost(BigDecimal.valueOf(0));
            orders.setPoint(0L);
            flag = ordersService.updateById(orders);
            if(flag){
                msg = "已成功取消整个预约订单！";
            }else{
                msg = "取消整个预约订单失败！";
            }
        }else{
            flag = fieldBookService.updateById(fieldBook);

            switch (fieldBook.getStatus()){
                case 2:
                    if(flag){
                       msg = "入场码正确！用户可入场！";
                    }else{
                        msg = "入场失败！";
                    }
                    break;
                case 3:
                case 4:
                    if(flag){
                        if(ObjectUtil.isNotNull(orders)&&orders.getStatus()!=0){
                            if(orders.getPoint()>0 || orders.getCost().compareTo(BigDecimal.valueOf(0))==1&&beforeUpdateStatus!=0){
                                if(orders.getPoint()>0){
                                    pointJournalService.pointInto(orders,0);
                                }
                                if(orders.getCost().compareTo(BigDecimal.valueOf(0))==1&&beforeUpdateStatus!=0){
                                    balanceJournalService.balanceInto(orders,0,fieldBook.getId());
                                }
                            }
                        }
                        if(fieldBook.getStatus()==3){
                            msg = "取消预约成功！";
                        }else if(fieldBook.getStatus()==4){
                            msg = "撤销预约成功！";
                        }
                        //检查相同订单是否还有有效项，没有就关闭订单
                        LambdaQueryWrapper<FieldBook> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(FieldBook::getOid,orders.getId()).in(FieldBook::getStatus,0,1,2,6);
                        if(fieldBookService.count(queryWrapper)==0){
                            orders.setStatus(2);
                            ordersService.updateById(orders);
                        }
                    }else{
                        if(fieldBook.getStatus()==3){
                            msg = "取消预约失败！";
                        }else if(fieldBook.getStatus()==4){
                            msg = "撤销预约失败！";
                        }
                    }
                    break;
            }
        }

        if(flag){
            return ResultUtils.success(msg);
        }else{
            return ResultUtils.error(msg);
        }
    }

    @DeleteMapping("/{ids}")
    public ResultVO deleteFieldBookByIds(@PathVariable("ids") String ids){
        List<Long> deleteIds = Convert.toList(Long.class,ids.split(","));
        if (Convert.toBool(fieldBookService.deleteFieldByIds(deleteIds))){
            return ResultUtils.success("取消建立预约订单成功！");
        }else{
            return ResultUtils.error("取消建立预约订单失败！");
        }
    }
}
